/*
 * RedisHelper.cpp
 *
 *  Created on: 2013年8月19日
 *      Author: sun
 */

#include "RedisAdaptor.h"
#include "Framework.h"
#include <hiredis/hiredis.h>

namespace sdfs {

RedisAdaptor::RedisAdaptor(ServerConfig *config) {
	m_rc = NULL;
	m_config = config;
}

RedisAdaptor::~RedisAdaptor() {
	if(m_rc != NULL)
		redisFree(m_rc);
	m_rc = NULL;
}

int RedisAdaptor::Connect()
{
	struct timeval timeout = { 1, 500000 }; // 1.5 seconds
	m_rc = redisConnectWithTimeout(m_config->strIp, m_config->nPort, timeout);
	if (m_rc == NULL || m_rc->err) {
		if (m_rc) {
			printf("Connection error: %s\n", m_rc->errstr);
			redisFree(m_rc);
		} else {
			printf("Connection error: can't allocate redis context\n");
		}
		return 1;
	}
	return 0;
}

void RedisAdaptor::Command(RedisReply &reply,const char *cmd, ...)
{
	va_list ap;
	va_start(ap,cmd);
	reply = (redisReply*)redisvCommand(m_rc,cmd,ap);
	va_end(ap);
}

int RedisAdaptor::DisConnect()
{
	redisFree(m_rc);
	m_rc = NULL;
	return 0;
}

RedisAdaptor *RedisAdaptor::Clone()
{
	return new RedisAdaptor(this->m_config);
}

} /* namespace sdfs */
